﻿using System.Windows.Forms;

namespace Seagull.Controls
{
    public class MultiRowContainer : TableLayoutPanel
    {
        private Control _defaultControl;

        private bool _isShowingDefaultControl = false;

        /// <summary>
        /// Gets or sets the default control to display when there are no child controls.
        /// </summary>
        /// <value>
        /// The default control.
        /// </value>
        public Control DefaultControl
        {
            get { return _defaultControl; }
            set
            {
                _defaultControl = value;
                if(Controls.Count == 0 && _defaultControl != null)
                {
                    AddControlInternal(_defaultControl);
                    _isShowingDefaultControl = true;
                }
            }
        }

        public void AddControl(Control control)
        {
            if(_isShowingDefaultControl)
            {
                RemoveControlInternal(_defaultControl);
                _isShowingDefaultControl = false;
            }
            AddControlInternal(control);
        }

        public void RemoveControl(Control control)
        {
            RemoveControlInternal(control);
            if(Controls.Count == 0 && _defaultControl != null)
            {
                AddControlInternal(_defaultControl);
                _isShowingDefaultControl = true;
            }
        }

        private void AddControlInternal(Control control)
        {
            if(Controls.Count == RowCount)
            {
                AddRow();
            }
            control.Dock = DockStyle.Fill;
            Controls.Add(control, 0, Controls.Count);
        }

        private void RemoveControlInternal(Control control)
        {
            var row = GetRow(control);
            Controls.Remove(control);
            for(var i = row + 1; i < RowCount; i++)
            {
                var controlOnNextRow = GetControlFromPosition(0, i);
                if(controlOnNextRow != null)
                {
                    SetRow(controlOnNextRow, i - 1);
                }
            }
            if(RowCount > 1)
            {
                RemoveLasRow();
            }
        }

        private void AddRow()
        {
            RowCount++;
            RowStyles.Add(new RowStyle(SizeType.Percent, 50));
        }

        private void RemoveLasRow()
        {
            RowStyles.RemoveAt(RowStyles.Count - 1);
            RowCount--;
        }
    }
}